<?php
/**
 * Created by PhpStorm.
 * User: luojinyi
 * Date: 2018/3/10
 * Time: 下午5:15
 */

namespace App\Http\Controllers\Api\Permission;

use App\Http\Controllers\Api\BaseAdminController;
use App\Http\Requests\Permission\MenuRequest;
use App\Http\Requests\Role\ShowRequest;
use App\Http\Requests\Role\RoleToUserRequest;
use App\Http\Requests\Role\UpdateRequest;
use App\Http\Requests\Role\StoreRequest;
use App\Http\Requests\Role\SingleRequest;
use App\Http\Requests\Role\DeleteRequest;
use App\Http\Requests\Role\AllRequest;
use App\Http\Transformers\RoleTransformer;
use App\Http\Transformers\SingleRoleTransformer;
use App\Services\RoleService;

/**
 * 角色管理
 * 该控制器只做两件事情：1、接收参数 2、dingo返回响应及其数据
 * 其他数据处理、外部服务、数据库查询等剥离至 Service和 Repository
 * Class RoleController
 * @package App\Http\Controllers\Api\Permission
 */
class RoleController extends BaseAdminController
{
    /**
     * @var RoleService 注入的RoleService 外部服务
     */
    protected $role_service;

    /**
     * RoleController constructor.
     * @param RoleService $roleService
     */
    public function __construct(RoleService $roleService){
        $this->role_service = $roleService;
    }

    /**
     * 获取角色列表
     */
    public function rolePages(ShowRequest $request){

        $name = $request->get('name');
        $limit = $request->get('limit');

        $page = $this->role_service->getRolePages($name, $limit);

        return $this->response->paginator($page, new RoleTransformer());
    }

    /**
     * 创建角色，并授权限
     */
    public function add(StoreRequest $request){
        $data = $request->all();

        $handle = $this->role_service->postRole($data);

        if($handle['status']){
            return $this->response->accepted('', '新增角色成功！');
        }

        $this->response->errorBadRequest($handle['msg']);
    }

    /**
     * 编辑角色及其权限
     */
    public function update(UpdateRequest $request){
        $data = $request->all();

        $handle = $this->role_service->updateRole($data);

        if($handle['status']){
            return $this->response->accepted('', '编辑角色成功！');
        }

        $this->response->errorBadRequest($handle['msg']);
    }

    /**
     * 获取单条角色数据
     */
    public function single(SingleRequest $request){
        $id = $request->get('id');

        $data = $this->role_service->getSingleRole($id);

        return $this->response->item($data, new SingleRoleTransformer());
    }

    /**
     * 获取所有角色列表
     */
    public function roleList(AllRequest $request){
        $allData = $this->role_service->getRoleList();

        return $this->response->collection($allData, new RoleTransformer());
    }

    /**
     * 删除角色
     */
    public function delete(DeleteRequest $request){
        $ids = $request->get('ids');

        if( $this->role_service->deleteRole($ids) ){
            return $this->response->created('', '删除成功');
        }
        $this->response->errorInternal('删除失败，请重试！');
    }

}
